//
//  UIDelegate.m
//  ScheduleMail
//
//  Created by jihoon on 13. 1. 9..
//  Copyright (c) 2013년 조지훈. All rights reserved.
//

#import "UIDelegate.h"

@implementation UIDelegate
- (void)webView:(WebView *)sender runOpenPanelForFileButtonWithResultListener:(id < WebOpenPanelResultListener >)resultListener
{
    // Create the File Open Dialog class.
    NSOpenPanel* openDlg = [NSOpenPanel openPanel];
    
    [openDlg setAllowsMultipleSelection:NO];
    [openDlg setFloatingPanel:NO];
    // Enable the selection of files in the dialog.
    [openDlg setCanChooseFiles:YES];
    
    // Enable the selection of directories in the dialog.
    [openDlg setCanChooseDirectories:NO];
    
    
    if([openDlg runModal]== NSOKButton)
    {
        NSArray* files = [openDlg URLs];
        NSString* fileName = [[files objectAtIndex:0] path]; //i];
        [resultListener chooseFilename:fileName];
    }
    
}

- (BOOL)webView:(WebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame
{
    NSAlert *alertDlg = [NSAlert alertWithMessageText:message defaultButton:@"확인" alternateButton:@"취소" otherButton:nil informativeTextWithFormat:@""];
    if([alertDlg runModal] == NSAlertDefaultReturn){
        return YES;
    };
    
    
    return NO;
}

- (void)webView:(WebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame
{
    NSAlert *alertDlg = [NSAlert alertWithMessageText:message defaultButton:@"확인" alternateButton:nil otherButton:nil informativeTextWithFormat:@""];
    [alertDlg setIcon:nil];
    [alertDlg runModal];
}

- (void)webView:(WebView *)webView decidePolicyForMIMEType:(NSString *)type request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id < WebPolicyDecisionListener >)listener
{
    if(![type isLike:@"text/html"])
    {
        [listener download];
        NSLog(@"download");
        return;
    }
    
    [listener use];
    return;
    
}

- (void)download:(NSURLDownload *)download decideDestinationWithSuggestedFilename:(NSString *)filename
{
    NSOpenPanel* openDlg = [NSOpenPanel openPanel];
    
    [openDlg setAllowsMultipleSelection:NO];
    [openDlg setFloatingPanel:NO];
    // Enable the selection of files in the dialog.
    [openDlg setCanChooseFiles:NO];
    // Enable the selection of directories in the dialog.
    [openDlg setCanChooseDirectories:YES];
    
    NSString *dest;
    if([openDlg runModal]== NSOKButton){
        NSArray* files = [openDlg URLs];
        NSString* documentsDirectory = [[files objectAtIndex:0] path]; //i];
        dest = [documentsDirectory stringByAppendingPathComponent:filename];
        
    }else {
        dest = [[NSHomeDirectory() stringByAppendingPathComponent:@"Downloads"] stringByAppendingPathComponent:filename];
    }
    [download setDestination:dest allowOverwrite:NO];
}

@end
